const Order = require('../models/Order');
const MenuItem = require('../models/MenuItem');
const Coupon = require('../models/Coupon');
const { validationResult } = require('express-validator');
const { logger } = require('../utils/logger');
const MenuCategory = require('../models/MenuCategory');
const User = require('../models/User');

/**
 * 订单管理控制器
 */
class OrderController {
  /**
   * 创建订单
   */
  static async createOrder(req, res) {
    try {
      console.log('📝 创建订单请求数据:', JSON.stringify(req.body, null, 2));
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        console.log('❌ 订单验证失败:', errors.array());
        return res.status(400).json({
          success: false,
          message: '输入验证失败',
          errors: errors.array()
        });
      }

      // 优先使用请求体中的user_id，如果没有则使用认证用户ID，最后才是null（匿名订单）
      const userId = req.body.user_id || (req.user ? req.user.id : null);
      const { items, coupon_code, user_id, ...orderData } = req.body;

      // 验证订单项
      if (!items || !Array.isArray(items) || items.length === 0) {
        return res.status(400).json({
          success: false,
          message: '订单项不能为空'
        });
      }

      // 计算订单金额 - 含税定价系统
      let subtotalIncludingTax = 0;
      let subtotalCashVoucher = 0;
      const orderItems = [];

      for (const item of items) {
        console.log(`🔍 查找菜品ID: ${item.menu_item_id}`);
        const menuItem = await MenuItem.findById(item.menu_item_id);
        console.log(`📋 菜品查找结果:`, menuItem);
        if (!menuItem) {
          console.log(`❌ 菜品ID ${item.menu_item_id} 不存在`);
          return res.status(400).json({
            success: false,
            message: `菜品ID ${item.menu_item_id} 不存在`
          });
        }

        if (!menuItem.is_available) {
          return res.status(400).json({
            success: false,
            message: `菜品 ${menuItem.name} 暂不可用`
          });
        }

        const itemTotal = menuItem.price * item.quantity;
        subtotalIncludingTax += itemTotal;
        
        // 如果是现金券，单独记录
        if (menuItem.is_cash_voucher) {
          subtotalCashVoucher += itemTotal;
        }

        orderItems.push({
          menu_item_id: item.menu_item_id,
          quantity: item.quantity,
          unit_price: menuItem.price,
          total_price: itemTotal,
          is_cash_voucher: !!menuItem.is_cash_voucher,
          notes: item.notes || ''
        });
      }

      // 计算税前金额 - 含税定价除以1.09得到税前金额
      // 现金券免税，其他商品按含税定价计算税前金额
      const taxRate = 0.09;
      const subtotalTaxable = subtotalIncludingTax - subtotalCashVoucher;
      const subtotalBeforeGST = subtotalTaxable / (1 + taxRate) + subtotalCashVoucher;

      // 处理优惠券（基于税前金额，排除现金券）
      let discountAmount = 0;
      let couponId = null;
      
      if (coupon_code) {
        const discountBase = subtotalBeforeGST - subtotalCashVoucher;
        
        const couponValidation = await Coupon.validateCoupon(
          coupon_code, 
          userId, 
          discountBase, 
          orderItems
        );
        
        if (!couponValidation.valid) {
          return res.status(400).json({
            success: false,
            message: couponValidation.message
          });
        }

        const coupon = couponValidation.coupon;
        couponId = coupon.id;
        
        discountAmount = await Coupon.calculateDiscount(coupon, discountBase, orderItems);
      }

      // 计算最终税前小计（扣除折扣后）
      const subtotalAfterDiscount = subtotalBeforeGST - discountAmount;
      
      // 计算GST：对非现金券的税前金额计算税费
      const taxableAfterDiscount = subtotalAfterDiscount - subtotalCashVoucher;
      const taxAmount = Math.max(0, taxableAfterDiscount * taxRate);

      // 最终总价：税前小计（已扣折扣）+ GST
      const totalAmount = subtotalAfterDiscount + taxAmount;

      // 创建订单数据
      const finalOrderData = {
        ...orderData,
        user_id: userId,
        // 保存税前小计（折扣前）
        subtotal: Math.round(subtotalBeforeGST * 100) / 100,
        tax_amount: Math.round(taxAmount * 100) / 100,
        discount_amount: Math.round(discountAmount * 100) / 100,
        delivery_fee: 0,
        total_amount: Math.round(totalAmount * 100) / 100,
        coupon_id: couponId
      };

      // 创建订单
      const order = await Order.create(finalOrderData, orderItems);
      console.log('OrderController: Order.create returned:', order);
      console.log('OrderController: order.id =', order.id);

      // 如果使用了优惠券，增加使用次数
      if (couponId) {
        await Coupon.incrementUsage(couponId);
      }

      // 获取完整订单信息
      const fullOrder = await Order.getOrderWithItems(order.id);
      console.log('OrderController: fullOrder =', fullOrder);

      res.status(201).json({
        success: true,
        data: fullOrder,
        message: '订单创建成功'
      });
    } catch (error) {
      logger.error('创建订单失败:', error);
      res.status(500).json({
        success: false,
        message: '创建订单失败',
        error: error.message
      });
    }
  }

  /**
   * 获取用户订单列表
   */
  static async getUserOrders(req, res) {
    try {
      const userId = req.user.id;
      const {
        status,
        order_type,
        page = 1,
        limit = 20,
        sort_by = 'created_at',
        sort_order = 'DESC'
      } = req.query;

      const options = {
        page: parseInt(page),
        limit: parseInt(limit),
        sort_by,
        sort_order
      };

      if (status) options.status = status;
      if (order_type) options.order_type = order_type;

      const orders = await Order.findByUserId(userId, options);

      res.json({
        success: true,
        data: orders,
        message: '获取订单列表成功'
      });
    } catch (error) {
      logger.error('获取订单列表失败:', error);
      res.status(500).json({
        success: false,
        message: '获取订单列表失败',
        error: error.message
      });
    }
  }

  /**
   * 获取订单详情
   */
  static async getOrderDetail(req, res) {
    try {
      const { id } = req.params;
      const userId = req.user.id;

      const order = await Order.getOrderWithItems(id);
      
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 检查订单是否属于当前用户（非管理员）
      const isAdmin = req.user.membership_level === 'admin';
      if (!isAdmin && order.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权访问此订单'
        });
      }

      res.json({
        success: true,
        data: order,
        message: '获取订单详情成功'
      });
    } catch (error) {
      logger.error('获取订单详情失败:', error);
      res.status(500).json({
        success: false,
        message: '获取订单详情失败',
        error: error.message
      });
    }
  }

  /**
   * 根据订单号获取订单
   */
  static async getOrderByNumber(req, res) {
    try {
      const { orderNumber } = req.params;
      const userId = req.user.id;

      const order = await Order.findByOrderNumber(orderNumber);
      
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 检查订单是否属于当前用户（非管理员）
      const isAdmin = req.user.membership_level === 'admin';
      if (!isAdmin && order.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权访问此订单'
        });
      }

      // 获取完整订单信息
      const fullOrder = await Order.getOrderWithItems(order.id);

      res.json({
        success: true,
        data: fullOrder,
        message: '获取订单详情成功'
      });
    } catch (error) {
      logger.error('根据订单号获取订单失败:', error);
      res.status(500).json({
        success: false,
        message: '获取订单失败',
        error: error.message
      });
    }
  }

  /**
   * 更新订单状态
   */
  static async updateOrderStatus(req, res) {
    try {
      const errors = validationResult(req);
      if (!errors.isEmpty()) {
        return res.status(400).json({
          success: false,
          message: '输入验证失败',
          errors: errors.array()
        });
      }

      const { id } = req.params;
      const { status, estimated_time } = req.body;
      const userId = req.user.id;

      // 获取订单信息
      const order = await Order.findById(id);
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 检查权限：用户只能取消自己的订单，管理员可以更新任何状态
      const isAdmin = req.user.membership_level === 'admin';
      if (!isAdmin) {
        if (order.user_id !== userId) {
          return res.status(403).json({
            success: false,
            message: '无权操作此订单'
          });
        }
        
        if (status !== 'cancelled') {
          return res.status(403).json({
            success: false,
            message: '用户只能取消订单'
          });
        }
        
        if (order.status !== 'pending') {
          return res.status(400).json({
            success: false,
            message: '只能取消待处理的订单'
          });
        }
      }

      // 更新订单状态
      const additionalData = {};
      if (estimated_time) {
        additionalData.estimated_time = estimated_time;
      }

      const success = await Order.updateStatus(id, status, additionalData);
      
      if (!success) {
        return res.status(500).json({
          success: false,
          message: '更新订单状态失败'
        });
      }

      res.json({
        success: true,
        message: '订单状态更新成功'
      });
    } catch (error) {
      logger.error('更新订单状态失败:', error);
      res.status(500).json({
        success: false,
        message: '更新订单状态失败',
        error: error.message
      });
    }
  }

  /**
   * 取消订单
   */
  static async cancelOrder(req, res) {
    try {
      const { id } = req.params;
      const userId = req.user.id;

      const order = await Order.findById(id);
      if (!order) {
        return res.status(404).json({
          success: false,
          message: '订单不存在'
        });
      }

      // 检查订单是否属于当前用户
      if (order.user_id !== userId) {
        return res.status(403).json({
          success: false,
          message: '无权取消此订单'
        });
      }

      // 检查订单状态
      if (order.status !== 'pending') {
        return res.status(400).json({
          success: false,
          message: '只能取消待处理的订单'
        });
      }

      const success = await Order.updateStatus(id, 'cancelled');
      
      if (!success) {
        return res.status(500).json({
          success: false,
          message: '取消订单失败'
        });
      }

      res.json({
        success: true,
        message: '订单已取消'
      });
    } catch (error) {
      logger.error('取消订单失败:', error);
      res.status(500).json({
        success: false,
        message: '取消订单失败',
        error: error.message
      });
    }
  }

  /**
   * 更新支付状态
   */
  static async updatePaymentStatus(req, res) {
    try {
      const { id } = req.params;
      const { payment_status, payment_id } = req.body;

      const success = await Order.updatePaymentStatus(id, payment_status, payment_id);
      
      if (!success) {
        return res.status(404).json({
          success: false,
          message: '订单不存在或更新失败'
        });
      }

      res.json({
        success: true,
        message: '支付状态更新成功'
      });
    } catch (error) {
      logger.error('更新支付状态失败:', error);
      res.status(500).json({
        success: false,
        message: '更新支付状态失败',
        error: error.message
      });
    }
  }

  /**
   * 获取订单统计
   */
  static async getOrderStatistics(req, res) {
    try {
      const {
        start_date,
        end_date,
        user_id
      } = req.query;

      const options = {};
      if (start_date) options.start_date = start_date;
      if (end_date) options.end_date = end_date;
      
      // 非管理员只能查看自己的统计
      const isAdmin = req.user.membership_level === 'admin';
      if (!isAdmin) {
        options.user_id = req.user.id;
      } else if (user_id) {
        options.user_id = user_id;
      }

      const statistics = await Order.getStatistics(options);

      res.json({
        success: true,
        data: statistics,
        message: '获取订单统计成功'
      });
    } catch (error) {
      logger.error('获取订单统计失败:', error);
      res.status(500).json({
        success: false,
        message: '获取订单统计失败',
        error: error.message
      });
    }
  }

  /**
   * 获取热门菜品
   */
  static async getPopularItems(req, res) {
    try {
      const {
        start_date,
        end_date,
        limit = 10
      } = req.query;

      const options = {
        limit: parseInt(limit)
      };
      
      if (start_date) options.start_date = start_date;
      if (end_date) options.end_date = end_date;

      const popularItems = await Order.getPopularItems(options);

      res.json({
        success: true,
        data: popularItems,
        message: '获取热门菜品成功'
      });
    } catch (error) {
      logger.error('获取热门菜品失败:', error);
      res.status(500).json({
        success: false,
        message: '获取热门菜品失败',
        error: error.message
      });
    }
  }

  /**
   * 管理员获取所有订单
   */
  static async getAllOrders(req, res) {
    try {
      // 管理员权限已通过requireAdmin中间件验证，无需重复检查

      const {
        status,
        order_type,
        user_id,
        start_date,
        end_date,
        page = 1,
        limit = 20,
        sort_by = 'created_at',
        sort_order = 'DESC'
      } = req.query;

      // 这里需要扩展Order模型来支持管理员查询
      // 暂时使用基础查询
      const options = {
        page: parseInt(page),
        limit: parseInt(limit),
        sort_by,
        sort_order
      };

      if (status) options.status = status;
      if (order_type) options.order_type = order_type;

      // 管理员可以查看所有订单
      let orders;
      if (user_id) {
        // 查询特定用户的订单
        orders = await Order.findByUserId(user_id, {
          status,
          order_type,
          page: parseInt(page),
          limit: parseInt(limit),
          sort_by,
          sort_order
        });
      } else {
        // 查询所有订单
        orders = await Order.findAll({
          status,
          order_type,
          start_date,
          end_date,
          page: parseInt(page),
          limit: parseInt(limit),
          sort_by,
          sort_order
        });
      }

      res.json({
        success: true,
        data: orders,
        message: '获取订单列表成功'
      });
    } catch (error) {
      logger.error('获取所有订单失败:', error);
      res.status(500).json({
        success: false,
        message: '获取订单列表失败',
        error: error.message
      });
    }
  }

  /**
   * 获取分类销量统计（按已完成订单计算）
   */
  static async getCategorySales(req, res) {
    try {
      const { start_date, end_date, limit = 10 } = req.query;
      const options = { limit: parseInt(limit) };
      if (start_date) options.start_date = start_date;
      if (end_date) options.end_date = end_date;

      const rows = await Order.getCategorySales(options);

      // 拉取分类名称映射
      const categories = await MenuCategory.findAll();
      const catMap = new Map(categories.map(c => [c.id, c]));

      const data = (rows || []).map(r => ({
        category_id: r.category_id,
        category_name: catMap.get(r.category_id)?.name || '未分类',
        category_name_en: catMap.get(r.category_id)?.name_en || 'Uncategorized',
        total_quantity: Number(r.total_quantity || 0),
        order_count: Number(r.order_count || 0),
        total_revenue: Number((r.total_revenue || 0))
      }));

      res.json({ success: true, data, message: '获取分类销量成功' });
    } catch (error) {
      logger.error('获取分类销量失败:', error);
      res.status(500).json({ success: false, message: '获取分类销量失败', error: error.message });
    }
  }

  /**
   * 获取订单类型分布（按已完成订单计算）
   */
  static async getOrderTypeDistribution(req, res) {
    try {
      const { start_date, end_date } = req.query;
      const orders = await Order.findAll({ start_date, end_date, page: 1, limit: 5000 });
      const map = new Map();
      for (const o of (orders || [])) {
        if (String(o.status) !== 'completed') continue;
        const k = o.order_type || 'unknown';
        map.set(k, (map.get(k) || 0) + 1);
      }
      const data = Array.from(map.entries()).map(([type, count]) => ({ type, count }));

      return res.json({ success: true, data, message: '获取订单类型分布成功' });
    } catch (error) {
      logger.error('获取订单类型分布失败:', error);
      res.status(500).json({ success: false, message: '获取订单类型分布失败', error: error.message });
    }
  }

  /**
   * 获取支付方式分布（按已完成订单计算）
   */
  static async getPaymentMethodDistribution(req, res) {
    try {
      const { start_date, end_date } = req.query;
      const orders = await Order.findAll({ start_date, end_date, page: 1, limit: 5000 });
      const map = new Map();
      for (const o of (orders || [])) {
        if (String(o.status) !== 'completed') continue;
        const k = o.payment_method || 'unknown';
        map.set(k, (map.get(k) || 0) + 1);
      }
      const data = Array.from(map.entries()).map(([method, count]) => ({ method, count }));

      return res.json({ success: true, data, message: '获取支付方式分布成功' });
    } catch (error) {
      logger.error('获取支付方式分布失败:', error);
      res.status(500).json({ success: false, message: '获取支付方式分布失败', error: error.message });
    }
  }

  /**
   * 获取Top客户（按已完成订单总额排序）
   */
  static async getTopCustomers(req, res) {
    try {
      const { start_date, end_date, limit = 10 } = req.query;
      const orders = await Order.findAll({ start_date, end_date, status: 'completed', page: 1, limit: 10000 });
      const agg = new Map();
      for (const o of (orders || [])) {
        const uid = o.user_id;
        if (!uid) continue;
        const entry = agg.get(uid) || { order_count: 0, total_spent: 0 };
        entry.order_count += 1;
        entry.total_spent += Number(o.total_amount || 0) || 0;
        agg.set(uid, entry);
      }
      const userIds = Array.from(agg.keys());
      const users = await Promise.all(userIds.map(id => User.findById(id).catch(() => null)));
      const userMap = new Map(users.filter(Boolean).map(u => [u.id || u.user_id || u.userId, u]));

      let data = userIds.map(id => {
        const { order_count, total_spent } = agg.get(id);
        const u = userMap.get(id) || {};
        const name = u.name || u.nickname || u.email || `用户${id}`;
        const avg_order_value = order_count > 0 ? Number((total_spent / order_count).toFixed(2)) : 0;
        return { user_id: id, name, order_count, total_spent: Number(total_spent.toFixed(2)), avg_order_value };
      });

      data.sort((a, b) => b.total_spent - a.total_spent);
      const top = data.slice(0, parseInt(limit));

      return res.json({ success: true, data: top, message: '获取Top客户成功' });
    } catch (error) {
      logger.error('获取Top客户失败:', error);
      res.status(500).json({ success: false, message: '获取Top客户失败', error: error.message });
    }
  }
}

// 追加：扩展趋势接口与增强Dashboard统计
// 注意：为了尽量少改动，直接在模块末尾添加新方法，并在导出前插入。
class __OrderControllerExtensions {}

// 将扩展方法合并到 OrderController 原型上
Object.assign(OrderController, {
  async getOrderTypeTrend(req, res) {
    try {
      const { start_date, end_date, bucket = 'auto' } = req.query;

      const start = start_date ? new Date(start_date) : new Date(Date.now() - 6 * 86400000);
      const end = end_date ? new Date(end_date) : new Date();
      end.setHours(23, 59, 59, 999);
      const ms = end - start;
      const isHourly = bucket === 'hour' || (bucket === 'auto' && ms <= 2 * 86400000);

      const buckets = [];
      const cursor = new Date(start);
      const pad = (n) => (n < 10 ? '0' + n : '' + n);
      const makeBucketKey = (d) => {
        const y = d.getFullYear();
        const m = pad(d.getMonth() + 1);
        const da = pad(d.getDate());
        if (isHourly) {
          const h = pad(d.getHours());
          return `${y}-${m}-${da} ${h}:00`;
        }
        return `${y}-${m}-${da}`;
      };
      while (cursor <= end) {
        buckets.push(makeBucketKey(cursor));
        if (isHourly) cursor.setHours(cursor.getHours() + 1);
        else cursor.setDate(cursor.getDate() + 1);
      }

      let orders = [];
      try {
        orders = await Order.findAll({ start_date, end_date, page: 1, limit: 5000, sort_by: 'created_at', sort_order: 'ASC' });
      } catch (e) {
        orders = [];
      }

      const trendInit = Object.fromEntries(buckets.map(k => [k, new Map()]));
      const knownTypes = new Set();
      for (const o of (orders || [])) {
        const createdAt = o.created_at ? new Date(o.created_at) : null;
        if (!createdAt || isNaN(createdAt)) continue;
        const key = makeBucketKey(createdAt);
        if (!trendInit[key]) continue;
        if (String(o.status) !== 'completed') continue;
        const t = o.order_type || 'unknown';
        knownTypes.add(t);
        const m = trendInit[key];
        m.set(t, (m.get(t) || 0) + 1);
      }

      const typeKeys = Array.from(knownTypes.values());
      const series = typeKeys.map(k => ({ key: k, points: buckets.map(b => ({ time: b, count: (trendInit[b].get(k) || 0) })) }));

      return res.json({ success: true, data: { buckets, series, bucketType: isHourly ? 'hour' : 'day' }, message: '获取订单类型趋势成功' });
    } catch (error) {
      logger.error('获取订单类型趋势失败:', error);
      res.status(500).json({ success: false, message: '获取订单类型趋势失败', error: error.message });
    }
  },

  async getPaymentMethodTrend(req, res) {
    try {
      const { start_date, end_date, bucket = 'auto' } = req.query;

      const start = start_date ? new Date(start_date) : new Date(Date.now() - 6 * 86400000);
      const end = end_date ? new Date(end_date) : new Date();
      end.setHours(23, 59, 59, 999);
      const ms = end - start;
      const isHourly = bucket === 'hour' || (bucket === 'auto' && ms <= 2 * 86400000);

      const buckets = [];
      const cursor = new Date(start);
      const pad = (n) => (n < 10 ? '0' + n : '' + n);
      const makeBucketKey = (d) => {
        const y = d.getFullYear();
        const m = pad(d.getMonth() + 1);
        const da = pad(d.getDate());
        if (isHourly) {
          const h = pad(d.getHours());
          return `${y}-${m}-${da} ${h}:00`;
        }
        return `${y}-${m}-${da}`;
      };
      while (cursor <= end) {
        buckets.push(makeBucketKey(cursor));
        if (isHourly) cursor.setHours(cursor.getHours() + 1);
        else cursor.setDate(cursor.getDate() + 1);
      }

      let orders = [];
      try {
        orders = await Order.findAll({ start_date, end_date, page: 1, limit: 5000, sort_by: 'created_at', sort_order: 'ASC' });
      } catch (e) {
        orders = [];
      }

      const trendInit = Object.fromEntries(buckets.map(k => [k, new Map()]));
      const knownMethods = new Set();
      for (const o of (orders || [])) {
        const createdAt = o.created_at ? new Date(o.created_at) : null;
        if (!createdAt || isNaN(createdAt)) continue;
        const key = makeBucketKey(createdAt);
        if (!trendInit[key]) continue;
        if (String(o.status) !== 'completed') continue;
        const mth = o.payment_method || 'unknown';
        knownMethods.add(mth);
        const m = trendInit[key];
        m.set(mth, (m.get(mth) || 0) + 1);
      }

      const methodKeys = Array.from(knownMethods.values());
      const series = methodKeys.map(k => ({ key: k, points: buckets.map(b => ({ time: b, count: (trendInit[b].get(k) || 0) })) }));

      return res.json({ success: true, data: { buckets, series, bucketType: isHourly ? 'hour' : 'day' }, message: '获取支付方式趋势成功' });
    } catch (error) {
      logger.error('获取支付方式趋势失败:', error);
      res.status(500).json({ success: false, message: '获取支付方式趋势失败', error: error.message });
    }
  }
});

module.exports = OrderController;